package com.card.config;

import com.baomidou.mybatisplus.extension.exceptions.ApiException;
import com.card.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * token验证
 */
@Slf4j
@Configuration
public class UserLoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //http的header中获得token
        String token = request.getHeader(JwtUtils.header);
        //token不存在
        if (token == null || token.equals("")) throw new ApiException("请先登录");
        //验证token
        String sub = JwtUtils.validateToken(token);
        if (sub == null || sub.equals(""))
            throw new ApiException("token验证失败");
        //更新token有效时间 (如果需要更新其实就是产生一个新的token)
        if (JwtUtils.isNeedUpdate(token)){
            String newToken = JwtUtils.createToken(sub);
            response.setHeader(JwtUtils.header,newToken);
        }
        return true;
    }
}